GBML manual / Language

Variables, types and scope

A variable has exactly one type, decided the first time it is assigned, and one of four places it can live.

Four kinds of variable

WriteLivesVisible from
var speed = 2;this event's own call, until it returnsonly this event
hp = 10; (a bare name, declared in Create, or by a parent - see below)the instanceevery event of this object and its children
global.wave = 1;the whole gameanywhere
static hits = 0; inside a functionthat function, across every callonly inside that function

An instance variable (a bare name with no var) is the common case: hp, speed, target, anything an object needs to remember between one event and the next.

An instance variable must be declared one of two ways: a plain hp = 10; assigned in Create and nowhere else first, or inheriting one a parent object already declared that way (see below). Its type is free to come from anywhere in the object once it exists: declare it in Create (target = nothing; is enough - see Objects and instances for why nothing is a fine first value for a reference) and a later event, even a totally different one, can go on to fix or refine what it actually holds (target = instance_nearest(x, y, obj_enemy); in Step). What the declaration fixes is that the variable exists at all - not its type, and not what it starts out as beyond its first assignment.

// Create
hp = 10;

// Step
hp -= 1;          // fine - hp was declared in Create
hitponts -= 1;    // ERROR: hitponts is declared nowhere - not Create, not the
                   // a parent - so this is read as a typo of hp, not a
                   // second variable. Before this rule, a bare name like this anywhere in the
                   // object created a brand new instance variable instead.

A var local (declared inside a for/if/anywhere) is exempt - it was never an instance variable to begin with, so this rule has nothing to say about it. So is every built-in instance variable (x, hp is not one of them, but speed/direction/visible/... are - see Objects and instances for the full list) - those already exist on every instance before Create even runs, whichever event first touches them. And an assignment inside a with block declares (or uses) a variable on whichever instance the with is currently visiting, never the instance whose own code the with block happens to be written in - see Expressions and statements for that retargeting.

An object with no Create event and no parent has no instance variables at all - there is nowhere for one to be declared. Give it a Create event (even one line) the moment it needs to remember anything between events.

GBML gathers an object's instance variables from its Create event and its parent - see Objects and instances for how inheritance folds a parent's variables in: a child may go on assigning a variable its PARENT declared in the parent's own Create, from any of the child's own events, without redeclaring it itself. self and other (also covered there) are how you reach another instance's variables from inside a with block or a Collision event.

nothing is not a fourth scope - it is the value an instance-reference variable holds when it is not currently pointing at anything, the same way 0 is a value an int can hold. all is not a value at all; it only appears as the target of a with (Expressions and statements).

A variable has exactly one type

score = 0;          // int - fixed by this first assignment
score = "zero";      // ERROR: score is already an int, not a string

This is not a style rule, it is what makes the generated C++ correct: an instance variable becomes one field of one C++ type, decided once. If you genuinely need two different kinds of value over an object's life, that is two variables (score and score_text, say), not one variable that changes shape. See What is unavailable, and why for the full reasoning - it is the same reason GBML has no undefined.

int is the one exception, and only in one direction: assigning a fractional value to an int variable widens it to real from that point on. Nothing else ever changes a variable's type.

The types

TypeMeaningRoughly
inta whole numbera plain integer
reala fixed-point number, about ±524,288 with 1/4096 precision (though a real times a real is cut to 1/64 first)see Where the machine shows through for what that precision means in practice
booltrue/false, 0/1 in arithmetic
stringbounded text, 32 characters by default@capacity raises the bound - see below
array<T>a bounded array of one element type@capacity sets how many
struct Namea fixed-shape value typesee Structs and constructors
ref<obj>a reference to an instance of obj, or nothingsee Objects and instances
sprite, sound, song, room, font, tileset, path, effectan id for one of your project's own assetsassigned by the editor when you add the asset
paletteone of your project's palettes: a set of 16 or 256 colors that can stand in for a picture's own colorsmade in the editor; nothing means "the picture's own colors" - see Palettes
colora 15-bit color
list<T>, map<K,V>, grid<T>, stack<T>, queue<T>, set<T>bounded containerseach has a fixed capacity, like an array
functiona function written in place, with no captured state; it works only as the function handed to foreach, filter or keep, and cannot be kept in a variablesee Functions

Every container and every string is bounded - it has a fixed maximum size decided when you declare it, because the hardware has fixed memory and nothing on it can grow a heap allocation at run time. Writing past the bound never overwrites other memory, but what happens instead depends on how you wrote it. Joining strings with + or +=, or with the string functions such as string_join, clamps: the text is cut off at the bound, so a string that comes out shorter than you expected is the sign. list_add refuses instead and hands back false. A template string (the $"SCORE {score}" kind) is cut off the same way: it is built piece by piece in a buffer as big as the project's Longest string setting, and a piece that will not fit is cut off at that bound, so a text that comes out shorter than you expected is the sign. See Data containers for how the seven compare, which one to reach for, and the rules they all share.

A variable can hold an object

The type table above has no row for it, because it is not a type you write: a variable that is given an object's name (var kind = obj_zombie;) simply holds that object, and may be given another one later (kind = obj_brute;) without the 'was one type, now given another' message. It is used with instance_create, the other built-ins that ask for an object's name (instance_count, instance_nth, pos_free...), with and kind.hp; see Keeping an object in a variable.

Filling the gaps: the documentation tags

Most of the time GBML infers a type without help: from a literal, from an existing variable, or from what a built-in function's own API table entry says it returns. When it genuinely cannot - a function parameter with nothing calling it yet, or a variable's very first use being ambiguous

size rather than filling a gap - see below - and the tags are all optional: leave @capacity off and a container has room for 8.)

Despite the name, these are not just notes. The compiler reads them, and they change the program: @capacity decides how much memory a container gets, and the others decide the type of a variable, a parameter or a return value. Each of them can also be written as ordinary code, with no comment. Both ways are supported and neither is going away - see Writing a type out for the full table of which tag matches which written form (var scores: array<int, 5> = ..., function heal(amount: int): real, array_create(5, 0)). The tag versions below are still the ones the rest of this manual shows most.

/// @arg {real} spd        how fast, in pixels a frame
/// @returns {bool}
function try_move(spd) {
    // ...
    return true;
}

/// @type {array<int>}
scores = [];

/// @capacity 16
name = "";

If none of these resolve it, the compiler stops and names the exact comment to add - it does not guess, because guessing wrong here would mean guessing wrong about a C++ field's actual type.

grid<T> needs an extra number. Every other container's @capacity is a single total size, but a grid is two-dimensional - indexing it (board[# x, y], see Expressions and statements) needs to know its own WIDTH, not just how many cells it has in total. Write it as WxH:

/// @type {grid<int>}
/// @capacity 8x6
board = [];

declares an 8-wide, 6-tall grid (48 cells in total). A bare /// @capacity 48 on a grid<T> still works exactly like it does for any other container (a total size, 48 cells) - it just leaves the grid un-indexable, since nothing said how those 48 cells are arranged into rows. The compiler stops and names the fix the moment [# x, y] is actually tried on a grid with no WxH capacity - the same "it does not guess" rule as every other tag on this page, not a crash and not a wrong cell.

Globals

global.<name> is the one scope with no owner - not tied to an instance, a function call, or an object's Create event. It is declared the same way an instance variable is: the first time you assign it, anywhere in the project, with a plain =. Read it from as many objects as you like, and write it from whichever one should actually change it - that is the whole point of a global (a shared score, read by the HUD and written by whatever just scored):

To say what a global starts as when the game starts (and starts over), use the Globals section of the Code tab instead of an object's Create event.

// obj_game's own Create event
global.score = 0;

// obj_enemy's own Destroy event, elsewhere in the project entirely
global.score += 10;

// obj_hud's own Draw GUI event, elsewhere again
draw_text(4, 4, $"SCORE {global.score}");

No var, no separate file to declare it in first - the same /// @type//// @capacity comments described above work here too, above whichever assignment you want to fix the type from, if inference alone cannot decide it:

/// @type {real}
global.time_scale = 1.0;

A global you never assign anywhere is a compile error, not a silent no-op - global.scoer += 1; (a typo of score) is refused with the misspelling named, the same way an undeclared instance variable already is.

Only int, real and bool can be a global today - a string, an array/list/grid, a struct or an object reference cannot yet. Reaching for one of those gets a clear error naming the type, not a guess.

Lifetime. A global is ordinary memory that exists for as long as the game is running - it survives room_change/room_next/room_restart without you doing anything, which is the reason to reach for one instead of an instance variable that a room change might destroy along with its instance. It resets to zero only when the game itself restarts - powering the console off and on, or relaunching the ROM in an emulator; nothing about a room, a pause, or a cutscene touches it.

Globals and saving are two different things, on purpose. A global is live, in-memory state for while the game is running; save_set/save_commit are how a value survives a power cycle, in SRAM. Setting a global never touches SRAM, and loading a save never sets a global for you - the two compose instead of overlapping:

// game_start - load whatever was last saved, once, into the global the rest of the game reads
global.score = save_get("high_score", 0);

// wherever your own project decides a save actually happens
if (global.score > save_get("high_score", 0)) {
    save_set("high_score", global.score);
    save_commit();
}

Instance variables the engine already gives you

An instance does not start empty. Position, motion, the sprite it draws, its collision mask, and a handful of others already exist on every instance before your own create event runs a single line - Objects and instances lists them by group and explains what each one does.

See also: What GBML isExpressions and statementsStructs and constructorsWhat is unavailable, and whyData containersWriting a type out, instead of in a comment